import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/components/NetWorkImage/NetworkImageWidget.dart';
import 'package:sinosheets/components/no_data_widget.dart';
import 'package:sinosheets/components/recommended_shop_item.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/r.dart';
import 'package:sinosheets/route/route_utils.dart';
import 'package:sinosheets/utils/theme/style_utils.dart';
import 'package:sinosheets/components/flash_sale_product_item.dart';
import 'package:sinosheets/components/normal_product_item.dart';
import 'package:url_launcher/url_launcher.dart';

import 'logic.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  final HomeLogic logic = Get.put(HomeLogic());
  bool _showStickyHeader = false;
  int _currentSectionIndex = 0;
  bool _isScrollingToSection = false;

  // 为各个区域定义GlobalKey
  final GlobalKey _freeGiftsKey = GlobalKey();
  final GlobalKey _hotCategoriesKey = GlobalKey();
  final GlobalKey _recommendedShopsKey = GlobalKey();
  final Map<int, GlobalKey> _categoryKeys = {};

  // 吸顶导航栏的横向滚动控制器
  final ScrollController _stickyHeaderScrollController = ScrollController();

  // 性能优化：添加节流变量
  DateTime _lastScrollTime = DateTime.now();
  int _lastSectionIndex = 0;
  bool _lastShowStickyHeader = false;

  // 缓存计算结果
  final Map<int, double> _sectionHeights = {};

  @override
  void initState() {
    super.initState();
  }

  void _onScroll(double offset) {
    // 如果正在程序滚动到指定区域，暂停区域检测
    if (_isScrollingToSection) return;

    // 节流：限制滚动事件处理频率
    DateTime now = DateTime.now();
    if (now.difference(_lastScrollTime).inMilliseconds < 16) {
      // 约60fps
      return;
    }
    _lastScrollTime = now;

    // 当滚动超过搜索框和社媒区域的高度时显示吸顶导航
    bool shouldShowStickyHeader = offset > 150;
    if (shouldShowStickyHeader != _lastShowStickyHeader) {
      _lastShowStickyHeader = shouldShowStickyHeader;
      setState(() {
        _showStickyHeader = shouldShowStickyHeader;
      });
    }

    // 只有当有可显示的区域时才更新当前选中的区域
    if (_hasVisibleSections(Get.find<HomeLogic>())) {
      _updateCurrentSection(offset);
    }
  }

  /// 更新当前选中的区域
  void _updateCurrentSection(double scrollOffset) {
    // 获取HomeLogic实例
    final get = Get.find<HomeLogic>();

    // 使用更简单可靠的距离计算方法
    _updateCurrentSectionWithDistance(scrollOffset, get);
  }

  /// 使用距离计算更新当前选中的区域
  void _updateCurrentSectionWithDistance(double scrollOffset, HomeLogic get) {
    // 基础偏移量（顶部文案 + 搜索框 + 社交分享区域）
    double currentOffset = 120.r;
    double titleOffset = 150.r;

    // 检查Free Gifts区域
    if (get.zeroProductList.isNotEmpty) {
      double freeGiftsHeight = _getSectionHeight(0, get);

      if (scrollOffset >= currentOffset + titleOffset && scrollOffset < currentOffset + freeGiftsHeight) {
        if (_currentSectionIndex != 0 && _lastSectionIndex != 0) {
          _lastSectionIndex = 0;
          setState(() {
            _currentSectionIndex = 0;
          });
          _scrollToStickyHeaderButton(0);
        }
        return;
      }
      currentOffset += freeGiftsHeight;
    }

    // 检查Hot Categories区域
    if (get.hotCategoryList.isNotEmpty) {
      double hotCategoriesHeight = _getSectionHeight(1, get);

      if (scrollOffset >= currentOffset + titleOffset && scrollOffset < currentOffset + hotCategoriesHeight) {
        if (_currentSectionIndex != 1 && _lastSectionIndex != 1) {
          _lastSectionIndex = 1;
          setState(() {
            _currentSectionIndex = 1;
          });
          _scrollToStickyHeaderButton(1);
        }
        return;
      }
      currentOffset += hotCategoriesHeight;
    }

    // 检查推荐店铺区域
    if (get.frontShopList.isNotEmpty) {
      double recommendedShopsHeight = _getSectionHeight(2, get);

      if (scrollOffset >= currentOffset + titleOffset && scrollOffset < currentOffset + recommendedShopsHeight) {
        if (_currentSectionIndex != 2 && _lastSectionIndex != 2) {
          _lastSectionIndex = 2;
          setState(() {
            _currentSectionIndex = 2;
          });
          _scrollToStickyHeaderButton(2);
        }
        return;
      }
      currentOffset += recommendedShopsHeight;
    }

    // 检查分类商品区域
    for (int i = 0; i < get.categoryProductList.length; i++) {
      double categoryHeight = _getSectionHeight(i + 3, get); // 索引从3开始，因为前面有3个固定区域

      if (scrollOffset >= currentOffset + titleOffset && scrollOffset < currentOffset + categoryHeight) {
        int sectionIndex = i + 3; // 分类区域的索引从3开始
        if (_currentSectionIndex != sectionIndex && _lastSectionIndex != sectionIndex) {
          _lastSectionIndex = sectionIndex;
          setState(() {
            _currentSectionIndex = sectionIndex;
          });
          _scrollToStickyHeaderButton(sectionIndex);
        }
        return;
      }
      currentOffset += categoryHeight;
    }
  }

  /// 获取区域高度（带缓存）
  double _getSectionHeight(int sectionIndex, HomeLogic get) {
    if (_sectionHeights.containsKey(sectionIndex)) {
      return _sectionHeights[sectionIndex]!;
    }

    double height = 0;

    switch (sectionIndex) {
      case 0: // Free Gifts
        height = 20.r + 12.r + 350.r + 12.r + 32.r + 16.r; // 约442r
        break;
      case 1: // Hot Categories
        height = 20.r + 16.r + 250.r + 10.r; // 约296r
        break;
      case 2: // Recommended Shops
        height = 20.r + 16.r + 280.r + 10.r; // 约326r (调整高度以适配新的UI)
        break;
      default: // 分类商品区域
        int categoryIndex = sectionIndex - 3; // 从3开始
        if (categoryIndex >= 0 && categoryIndex < get.categoryProductList.length) {
          var category = get.categoryProductList[categoryIndex];
          var productList = category['list'] as List?;

          double baseHeight = 20.r + 20.r + 12.r + 12.r + 32.r + 12.r; // 约108r
          double gridHeight = 0;

          if (productList != null && productList.isNotEmpty) {
            int itemCount = (productList.length ~/ 2) * 2;
            int rows = (itemCount / 2).ceil();
            gridHeight = rows * 200.r;
          }

          height = baseHeight + gridHeight;
        }
        break;
    }

    _sectionHeights[sectionIndex] = height;
    return height;
  }

  /// 滚动到指定区域
  void _scrollToSection(int sectionIndex, HomeLogic get) {
    setState(() {
      _isScrollingToSection = true;
    });

    // 根据区域索引获取对应的GlobalKey
    GlobalKey? targetKey;
    switch (sectionIndex) {
      case 0: // Free Gifts
        if (get.zeroProductList.isNotEmpty) {
          targetKey = _freeGiftsKey;
        }
        break;
      case 1: // Hot Categories
        if (get.hotCategoryList.isNotEmpty) {
          targetKey = _hotCategoriesKey;
        }
        break;
      case 2: // Recommended Shops
        if (get.frontShopList.isNotEmpty) {
          targetKey = _recommendedShopsKey;
        }
        break;
      default: // 分类商品区域
        int categoryIndex = sectionIndex - 3; // 从3开始
        if (categoryIndex >= 0 && categoryIndex < get.categoryProductList.length) {
          targetKey = _categoryKeys[categoryIndex];
        }
        break;
    }

    if (targetKey != null && targetKey.currentContext != null) {
      // 使用Scrollable.ensureVisible来滚动到指定组件
      Scrollable.ensureVisible(
        targetKey.currentContext!,
        duration: Duration(milliseconds: 500),
        curve: Curves.easeInOut,
        alignment: 0.0, // 对齐到顶部
      ).then((_) {
        // 滚动完成后恢复区域检测
        Future.delayed(Duration(milliseconds: 100), () {
          setState(() {
            _isScrollingToSection = false;
          });
        });
      });
    } else {
      // 如果GlobalKey不可用，回退到原来的计算方法
      _scrollToSectionFallback(sectionIndex, get);
    }
  }

  /// 回退的滚动方法（使用计算距离）
  void _scrollToSectionFallback(int sectionIndex, HomeLogic get) {
    // 计算各个区域的大概位置
    double offset = 0;

    // 基础偏移量（顶部文案 + 搜索框 + 社交分享区域）
    offset += 120.r;

    // 根据区域索引计算偏移量
    switch (sectionIndex) {
      case 0: // Free Gifts
        if (get.zeroProductList.isNotEmpty) {
          offset += 0;
        }
        break;
      case 1: // Hot Categories
        if (get.hotCategoryList.isNotEmpty) {
          if (get.zeroProductList.isNotEmpty) {
            offset += 300.r; // Free Gifts区域高度
          } else {
            offset += 0;
          }
        }
        break;
      case 2: // Recommended Shops
        if (get.frontShopList.isNotEmpty) {
          if (get.zeroProductList.isNotEmpty) {
            offset += 300.r; // Free Gifts区域高度
          }
          if (get.hotCategoryList.isNotEmpty) {
            offset += 200.r; // Hot Categories 高度
          }
        }
        break;
      default: // 分类商品区域
        int categoryIndex = sectionIndex - 3; // 从3开始
        if (categoryIndex >= 0 && categoryIndex < get.categoryProductList.length) {
          // 累加前面所有区域的高度
          if (get.zeroProductList.isNotEmpty) {
            offset += 300.r; // Free Gifts区域高度
          }
          if (get.hotCategoryList.isNotEmpty) {
            offset += 200.r; // Hot Categories 高度
          }
          if (get.frontShopList.isNotEmpty) {
            offset += 200.r; // Recommended Shops 高度
          }
          offset += categoryIndex * 400.r; // 每个分类区域的大概高度
        }
        break;
    }

    // 如果吸顶导航栏显示，需要减去其高度
    if (_showStickyHeader) {
      offset -= 50.r;
    }

    // 确保偏移量不为负数
    offset = offset.clamp(0.0, double.infinity);

    // 使用PrimaryScrollController来控制滚动
    final scrollController = PrimaryScrollController.of(context);
    scrollController
        .animateTo(
      offset,
      duration: Duration(milliseconds: 500),
      curve: Curves.easeInOut,
    )
        .then((_) {
      // 滚动完成后恢复区域检测
      Future.delayed(Duration(milliseconds: 100), () {
        setState(() {
          _isScrollingToSection = false;
        });
      });
    });
  }

  ///顶部文案区
  Widget _topTextArea(HomeLogic get) {
    return Column(
      children: [
        SizedBox(height: 10.r),
        Center(
          child: Text(
            'Shop the Best, From China to the Rest',
            style: StyleUtils.ts_1f_16_600,
          ),
        ),
        SizedBox(height: 10.r),
      ],
    );
  }

  ///搜索框区
  Widget _searchArea(HomeLogic get) {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 10.r),
          child: Row(
            children: [
              // 搜索输入框
              Expanded(
                child: Container(
                  height: 44.r,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(22.r),
                    border: Border.all(color: Color(0xFFFF7D00), width: 1.r),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 10.r),
                  child: TextField(
                    controller: get.searchController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Enter or paste the name/link/No.',
                      hintStyle: TextStyle(color: Color(0xFFBDBDBD), fontSize: 10.r),
                      contentPadding: EdgeInsets.symmetric(vertical: 12.r),
                      suffixIcon: IconButton(
                        onPressed: () {
                          get.searchController.clear();
                          get.update();
                        },
                        icon: get.searchController.text.isNotEmpty
                            ? Icon(
                                Icons.close,
                                color: ColorUtils.c_1f1f1f,
                                size: 16.r,
                              )
                            : SizedBox.shrink(),
                      ),
                    ),
                    onChanged: (value) {
                      get.update();
                    },
                    onSubmitted: (value) {
                      get.onSearchClick();
                    },
                    style: TextStyle(fontSize: 12.r, color: ColorUtils.c_1f1f1f),
                  ),
                ),
              ),
              SizedBox(width: 8.r),
              // 搜索按钮
              GestureDetector(
                onTap: () {
                  get.onSearchClick();
                },
                child: Container(
                  height: 44.r,
                  padding: EdgeInsets.symmetric(horizontal: 20.r),
                  decoration: BoxDecoration(
                    color: Color(0xFFFF7D00),
                    borderRadius: BorderRadius.circular(22.r),
                    border: Border.all(color: Color(0xFFFF7D00), width: 1.r),
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    'Search',
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.r,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 10.r),
      ],
    );
  }

  ///社媒分享区
  Widget _socialMediaShareArea(HomeLogic get) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _CircleIconButton(
              icon: Image.asset(R.assetsImgIconSolidSimilar, width: 28.r, height: 28.r, fit: BoxFit.fill),
              backgroundColor: Colors.white,
              borderColor: Color(0xFFFF7D00),
              onTap: () {
                // TODO: 拍照逻辑
                launchUrl(Uri.parse('https://www.itaobuy.com?inviteCode=B2EDANTE'));
              },
            ),
            SizedBox(width: 32.r),
            _CircleIconButton(
              icon: Image.asset(R.assetsImgIconSolidDiscord, width: 28.r, height: 28.r, fit: BoxFit.fill),
              backgroundColor: Color(0xFF5865F2),
              onTap: () {
                // TODO: Discord 跳转
                launchUrl(Uri.parse('https://discord.com/invite/W7ppQk7yQR'));
              },
            ),
            SizedBox(width: 32.r),
            _CircleIconButton(
              icon: Image.asset(R.assetsImgIconSolidReddit, width: 28.r, height: 28.r, fit: BoxFit.fill),
              backgroundColor: Color(0xFFFF4500),
              onTap: () {
                // TODO: Reddit 跳转
                launchUrl(Uri.parse('https://www.reddit.com/r/itaobuyshare'));
              },
            ),
          ],
        ),
        SizedBox(height: 10.r),
      ],
    );
  }

  ///秒杀商品区
  Widget _flashSaleProductArea(HomeLogic get) {
    final zeroList = get.zeroProductList;

    if (zeroList.isEmpty) {
      return SizedBox.shrink(); // 如果为空则不显示整个区域
    }

    return Container(
      key: _freeGiftsKey,
      child: Column(
        children: [
          SizedBox(height: 16.r),
          Text('Free Gifts', style: TextStyle(color: Color(0xFFFF7D00), fontSize: 20.r, fontWeight: FontWeight.bold)),
          SizedBox(height: 12.r),
          GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: 12.r),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 16.r,
              crossAxisSpacing: 12.r,
              childAspectRatio: 0.68,
            ),
            itemCount: (zeroList.length ~/ 2) * 2,
            itemBuilder: (context, idx) {
              return FlashSaleProductItem(item: zeroList[idx]['mallProduct']);
            },
          ),
          SizedBox(height: 12.r),
          Center(
            child: GestureDetector(
              onTap: () {
                RouteUtils.toWebView(url: AppPrefix.seagoUrl);
              },
              child: Container(
                width: 80.r,
                height: 32.r,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16.r),
                ),
                alignment: Alignment.center,
                child: Text('More', style: TextStyle(color: Color(0xFF999999), fontSize: 14.r)),
              ),
            ),
          ),
          SizedBox(height: 16.r),
        ],
      ),
    );
  }

  ///分类商品区
  Widget _categoryProductArea(HomeLogic get) {
    final List categoryList = get.categoryProductList;

    if (categoryList.isEmpty) {
      return SizedBox.shrink(); // 如果为空则不显示整个区域
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        for (int i = 0; i < categoryList.length; i++) ...[
          Container(
            key: _categoryKeys[i] ??= GlobalKey(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 20.r),
                Center(
                  child: Text(
                    categoryList[i]['name'] ?? '',
                    style: TextStyle(
                      color: Color(0xFF222244),
                      fontSize: 20.r,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                SizedBox(height: 12.r),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12.r),
                  child: (categoryList[i]['list'] as List).isEmpty
                      ? NoDataWidget.emptyList(
                          title: 'No Products',
                          description: 'No products available in this category at the moment.',
                          showButton: false,
                        )
                      : GridView.builder(
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: (((categoryList[i]['list'] as List).length) ~/ 2) * 2,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            mainAxisSpacing: 16.r,
                            crossAxisSpacing: 12.r,
                            childAspectRatio: 0.63,
                          ),
                          itemBuilder: (context, idx) {
                            final item = (categoryList[i]['list'] as List)[idx];
                            return NormalProductItem(item: item);
                          },
                        ),
                ),
                SizedBox(height: 12.r),
                GestureDetector(
                  onTap: () {
                    RouteUtils.toCategoryProduct(categoryId: "${categoryList[i]['id']}", categoryName: categoryList[i]['name'] ?? '');
                  },
                  child: Center(
                    child: Container(
                      width: 80.r,
                      height: 32.r,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16.r),
                      ),
                      alignment: Alignment.center,
                      child: Text('More', style: TextStyle(color: Color(0xFF999999), fontSize: 14.r)),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  ///热门分类区
  Widget _hotCategoryArea(HomeLogic get) {
    final hotList = get.hotCategoryList;

    if (hotList.isEmpty) {
      return SizedBox.shrink(); // 如果为空则不显示整个区域
    }

    return Container(
      key: _hotCategoriesKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 20.r),
          Center(
            child: Text(
              'Hot Categories',
              style: TextStyle(
                color: ColorUtils.themeColor,
                fontSize: 20.r,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(height: 16.r),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.r),
            child: GridView.builder(
              shrinkWrap: true,
              padding: EdgeInsets.zero,
              physics: NeverScrollableScrollPhysics(),
              itemCount: (hotList.length ~/ 2) * 2,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 16.r,
                crossAxisSpacing: 16.r,
                childAspectRatio: 0.95,
              ),
              itemBuilder: (context, idx) {
                final item = hotList[idx];
                return _hotCategoryItem(item);
              },
            ),
          ),
          SizedBox(height: 12.r),
        ],
      ),
    );
  }

  Widget _hotCategoryItem(Map<String, dynamic> item) {
    // 取英文名
    String name = item['name'] ?? '';
    if (item['nameList'] is List) {
      final en = (item['nameList'] as List).firstWhere((e) => e['lang'] == 'en', orElse: () => null);
      if (en != null && en['content'] != null) {
        name = en['content'];
      }
    }
    return GestureDetector(
        onTap: () {
          RouteUtils.toCategoryProduct(categoryId: "${item['id']}", categoryName: name);
        },
        child: Container(
          decoration: BoxDecoration(
            color: Color(0xFFF7F7F7),
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.03),
                blurRadius: 4.r,
                offset: Offset(0, 2.r),
              ),
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 5.r),
              Expanded(
                  child: ClipRRect(
                borderRadius: BorderRadius.circular(12.r),
                child: NetworkImageWidget(
                  url: item['img'],
                  fit: BoxFit.contain,
                ),
              )),
              SizedBox(height: 10.r),
              Text(
                name,
                style: TextStyle(
                  fontSize: 16.r,
                  color: Color(0xFF222244),
                  fontWeight: FontWeight.w600,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 5.r),
            ],
          ),
        ));
  }

  ///推荐店铺区
  Widget _recommendedShopsArea(HomeLogic get) {
    final shopList = get.frontShopList;

    if (shopList.isEmpty) {
      return SizedBox.shrink(); // 如果为空则不显示整个区域
    }

    return Container(
      key: _recommendedShopsKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 20.r),
          Center(
            child: Text(
              'Recommended Shops',
              style: TextStyle(
                color: ColorUtils.themeColor,
                fontSize: 20.r,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(height: 16.r),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.r),
            child: GridView.builder(
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: (shopList.length ~/ 2) * 2,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 16.r,
                crossAxisSpacing: 16.r,
                childAspectRatio: 0.73,
              ),
              itemBuilder: (context, idx) {
                final item = shopList[idx];
                return RecommendedShopItem(item: item);
              },
            ),
          ),
          SizedBox(height: 10.r),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<HomeLogic>(builder: (get) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Image.asset(
            R.assetsImgSinosheets,
            width: 150.r,
            fit: BoxFit.fill,
          ),
          centerTitle: true,
        ),
        body: NotificationListener<ScrollNotification>(
          onNotification: (ScrollNotification notification) {
            if (notification is ScrollUpdateNotification) {
              _onScroll(notification.metrics.pixels);
            }
            return false;
          },
          child: EasyRefresh.builder(
            controller: get.controller,
            onRefresh: () async => await get.onRefresh(),
            onLoad: () async => await get.onLoad(),
            childBuilder: (context, physics) => CustomScrollView(
              physics: physics,
              slivers: [
                // 顶部文案区域
                SliverToBoxAdapter(child: _topTextArea(get)),
                // 搜索框区域
                SliverToBoxAdapter(child: _searchArea(get)),
                // 社媒分享区域
                SliverToBoxAdapter(child: _socialMediaShareArea(get)),
                // 吸顶导航栏
                if (_showStickyHeader && _hasVisibleSections(get))
                  SliverPersistentHeader(
                    pinned: true,
                    delegate: _StickyHeaderDelegate(
                      child: _buildStickyHeaderContent(get),
                    ),
                  ),
                // 主要内容区域
                SliverToBoxAdapter(
                  child: RepaintBoundary(
                    child: Column(
                      children: [
                        _flashSaleProductArea(get),
                        _hotCategoryArea(get),
                        _recommendedShopsArea(get),
                        _categoryProductArea(get),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  /// 构建吸顶导航栏内容
  Widget _buildStickyHeaderContent(HomeLogic get) {
    // 动态构建完整的标题列表，根据接口数据决定是否显示
    List<String> allTitles = [];

    // 检查Free Gifts是否有数据
    if (get.zeroProductList.isNotEmpty) {
      allTitles.add('Free Gifts');
    }

    // 检查Hot Categories是否有数据
    if (get.hotCategoryList.isNotEmpty) {
      allTitles.add('Hot Categories');
    }

    // 检查Recommended Shops是否有数据
    if (get.frontShopList.isNotEmpty) {
      allTitles.add('Recommended Shops');
    }

    // 添加从接口获取的分类名字
    for (var category in get.categoryProductList) {
      if (category['name'] != null && category['name'].toString().isNotEmpty) {
        allTitles.add(category['name']);
      }
    }

    // 如果没有可显示的标题，返回空容器
    if (allTitles.isEmpty) {
      return SizedBox.shrink();
    }

    return RepaintBoundary(
      child: Container(
        height: 50.r,
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.08),
              blurRadius: 12.r,
              offset: Offset(0, 4.r),
            ),
          ],
        ),
        child: NotificationListener<ScrollNotification>(
          onNotification: (ScrollNotification notification) {
            // 阻止水平滚动的通知向上传播，避免影响吸顶导航栏
            return true;
          },
          child: SingleChildScrollView(
            controller: _stickyHeaderScrollController,
            scrollDirection: Axis.horizontal,
            padding: EdgeInsets.symmetric(horizontal: 16.r),
            child: Row(
              children: allTitles.asMap().entries.map((entry) {
                int index = entry.key;
                String title = entry.value;
                bool isSelected = _currentSectionIndex == index;

                return RepaintBoundary(
                  child: Container(
                    key: ValueKey('sticky_header_$index'),
                    margin: EdgeInsets.only(right: 20.r),
                    padding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 8.r),
                    decoration: BoxDecoration(
                      gradient: isSelected
                          ? LinearGradient(
                              colors: [
                                ColorUtils.themeColor,
                                ColorUtils.themeColor.withValues(alpha: 0.8),
                              ],
                            )
                          : null,
                      color: isSelected ? null : Colors.transparent,
                      borderRadius: BorderRadius.circular(20.r),
                      border: Border.all(
                        color: isSelected ? ColorUtils.themeColor : ColorUtils.c_cccccc,
                        width: 1.r,
                      ),
                    ),
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _currentSectionIndex = index;
                        });
                        _scrollToSection(index, get);
                      },
                      child: Text(
                        title,
                        style: TextStyle(
                          color: isSelected ? Colors.white : ColorUtils.c_666666,
                          fontSize: 14.r,
                          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
        ),
      ),
    );
  }

  /// 滚动到吸顶导航栏的按钮
  void _scrollToStickyHeaderButton(int sectionIndex) {
    // 延迟执行，确保UI已经更新
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_stickyHeaderScrollController.hasClients) {
        // 计算目标按钮的位置
        double buttonWidth = 100.0; // 估算每个按钮的宽度
        double targetOffset = sectionIndex * buttonWidth;

        // 获取当前滚动位置和最大滚动范围
        double currentOffset = _stickyHeaderScrollController.offset;
        double maxOffset = _stickyHeaderScrollController.position.maxScrollExtent;

        // 确保目标位置在有效范围内
        targetOffset = targetOffset.clamp(0.0, maxOffset);

        // 只有当目标位置与当前位置差异足够大时才滚动
        if ((targetOffset - currentOffset).abs() > 20) {
          _stickyHeaderScrollController.animateTo(
            targetOffset,
            duration: Duration(milliseconds: 200), // 减少动画时间
            curve: Curves.easeOut, // 使用更快的缓动曲线
          );
        }
      }
    });
  }

  /// 判断是否有可显示的区域
  bool _hasVisibleSections(HomeLogic get) {
    return get.zeroProductList.isNotEmpty || get.hotCategoryList.isNotEmpty || get.frontShopList.isNotEmpty || get.categoryProductList.isNotEmpty;
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    _stickyHeaderScrollController.dispose();
    Get.delete<HomeLogic>();
    super.dispose();
  }
}

class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
  final Widget child;

  _StickyHeaderDelegate({required this.child});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => 50.r; // 吸顶导航栏的高度

  @override
  double get minExtent => 50.r; // 吸顶导航栏的高度

  @override
  bool shouldRebuild(_StickyHeaderDelegate oldDelegate) {
    return oldDelegate.child != child;
  }
}

class _CircleIconButton extends StatelessWidget {
  final Widget icon;
  final Color backgroundColor;
  final Color? borderColor;
  final VoidCallback? onTap;

  const _CircleIconButton({
    required this.icon,
    required this.backgroundColor,
    this.borderColor,
    this.onTap,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 40.r,
        height: 40.r,
        decoration: BoxDecoration(
          color: backgroundColor,
          shape: BoxShape.circle,
          border: borderColor != null ? Border.all(color: borderColor!, width: 2.r) : null,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.04),
              blurRadius: 8.r,
              offset: Offset(0, 2.r),
            ),
          ],
        ),
        child: Center(child: icon),
      ),
    );
  }
}
